#include "udebug.h"
#include "usocket.h"





#define LEN   1024
int kfd_clients[1024] = {0};


void add_to_clients(int fd_client)
{
    int i;
    for(i=0; i<1024; i++)
    {
        if(kfd_clients[i] == 0) {
            kfd_clients[i] = fd_client;
            break;
        }
    }
}


int main()
{
    int fd_server = usocket_tcp_create_server(8080);
    ulogdbg("fd_server=%d.\n", fd_server);

    fd_set fdsr;
    int i;
    int ret;
    int fd_client;

    int maxfd;
    maxfd = fd_server;

    while(1) 
    {
        FD_ZERO(&fdsr);
        FD_SET(fd_server, &fdsr);

        for(i=0; i<1024; i++)
        {
            if(kfd_clients[i] != 0) {
                FD_SET(kfd_clients[i], &fdsr);
            }
        }

        /*block unitl fd could be read.*/
        ret = select(maxfd+1, &fdsr, NULL, NULL, /*&tv*/NULL);
        if(ret < 0) {
            ulogerr("select error.\n");
            break;
        }
        else if(ret == 0) {
            ulogerr("select timeout.\n");
            continue;
        }

        if(FD_ISSET(fd_server, &fdsr)) {
            fd_client = accept(fd_server, NULL, NULL); 
            ulogdbg("%10s : %d.\n", "accpet", fd_client);
            add_to_clients(fd_client);
            maxfd = fd_client>maxfd?fd_client:maxfd;
        }

        for(i=0; i<1024; i++)
        {
            fd_client = kfd_clients[i];
            if(!((fd_client != 0) && (FD_ISSET(fd_client, &fdsr)))) {
                continue;
            }

            char buf[LEN];
            memset(buf, 0, LEN);

            int n = read(fd_client, buf, LEN-1);
            //ulogdbg("n=%d\n", n);

            if(0 == n) {
                ulogdbg("%10s : %d\n", "close", fd_client);
                close(fd_client);
                kfd_clients[i] = 0;
                continue;
            }

            //ulogdbg("---------------------------------------\n""%s\n""-----------------------------------\n", buf);
            ulogdbg("%10s : %s\n", "receive", buf);

            size_t sizec = strlen(buf);
            int nwrite = 0;
            while(nwrite != sizec)
            {
                int nw = write(fd_client, buf+nwrite, sizec-nwrite);
                if(nw <= 0) {
                    printf("write error.(%d %s)\n", errno, strerror(errno));
                    sleep(1);
                    continue;
                }

                nwrite += nw;
                //printf("====== wrote : %d .\n", nwrite);
            }
        }
    }

    close(fd_server);

    return 0;
}
